<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CallTaskVO } from '#/api/contact/task/call/model';

import { useRouter } from 'vue-router';

// import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
// import { VbenIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { MailOutlined, MessageOutlined } from '@ant-design/icons-vue';
import {
  Button,
  message,
  Modal,
  Popconfirm,
  Progress,
  Space,
  Tag,
} from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  // callTaskUpdateStatus,
  callTaskExport,
  callTaskInfo,
  callTaskIsCallUser,
  callTaskPage,
  callTaskRemove,
} from '#/api/contact/task/call';
import { DetailsModal } from '#/components/modal';
import { commonDownloadExcel } from '#/utils/file/download';
import emailPreviewModal from '#/views/config/template/email/components/email-preview-modal.vue';
import smsPreviewModal from '#/views/config/template/sms/components/sms-preview-modal.vue';

import callTaskDataDrawer from './call-task-data-drawer.vue';
import callTaskDrawer from './call-task-drawer.vue';
import { columns, detailsSchema, querySchema } from './data';

// const { hasAccessByCodes } = useAccess();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 90,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  fieldMappingTime: [
    [
      'taskTime',
      ['params[startDate]', 'params[endDate]'],
      ['YYYY-MM-DD', 'YYYY-MM-DD'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
  // columns: columns(),
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await callTaskPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'contact-task-call-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [CallTaskDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: callTaskDrawer,
  destroyOnClose: true,
});

const [CallTaskDetailsModal, detailsModalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

function handlePreview(record: CallTaskVO) {
  detailsModalApi.setData(record);
  detailsModalApi.open();
}

function handleAdd() {
  drawerApi.setData({});
  drawerApi.open();
}

async function handleEdit(row: CallTaskVO) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleDelete(row: CallTaskVO) {
  await callTaskRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: CallTaskVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await callTaskRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(
    callTaskExport,
    '呼叫任务数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

// async function statusUpdate(row: CallTaskVO) {
//   await callTaskUpdateStatus({ id: row.id, status: row.status });
// }

// 预览短信模板
const [SmsPreviewModal, smsPreviewModalApi] = useVbenModal({
  connectedComponent: smsPreviewModal,
});

async function handlePreviewSms(smsTemplateId: number | string) {
  smsPreviewModalApi.setData({ id: smsTemplateId });
  smsPreviewModalApi.open();
}

// 预览邮件模板
const [EmailPreviewModal, emailPreviewModalApi] = useVbenModal({
  connectedComponent: emailPreviewModal,
});

async function handlePreviewEmail(emailTemplateId: number | string) {
  emailPreviewModalApi.setData({ id: emailTemplateId });
  emailPreviewModalApi.open();
}

// 去联络工作台
const router = useRouter();

async function handleToCall(row: CallTaskVO) {
  try {
    row.loading = true;
    const result = await callTaskIsCallUser(row.id);
    if (result) {
      await router.push({
        path: '/contact/task/callWorkbench',
        query: {
          taskId: row.id,
        },
      });
    } else {
      message.warning('您不是任务中的呼叫人员');
    }
  } catch (error) {
    console.error(error);
  } finally {
    row.loading = false;
  }
}

// 查看任务人员数据
const [CallTaskDataDrawer, callTaskDataDrawerApi] = useVbenDrawer({
  connectedComponent: callTaskDataDrawer,
  destroyOnClose: true,
});

function handleViewTaskData(row: CallTaskVO) {
  callTaskDataDrawerApi.setData({ taskId: row.id, taskName: row.name });
  callTaskDataDrawerApi.open();
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable>
      <template #table-title>
        <main-title text="呼叫任务列表" />
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['call:task:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['call:task:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['call:task:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #employeeNum="{ row }">
        <Button type="link" @click="handleViewTaskData(row)">
          {{ row.employeeNum || 0 }}
        </Button>
      </template>
      <template #completionRate="{ row }">
        <Progress type="circle" :percent="row.completionRate || 0" :size="50" />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['call:task:query']"
            @click.stop="handlePreview(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button
            v-access:code="['call:task:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <ghost-button
            :loading="row.loading"
            class="btn-success"
            @click="handleToCall(row)"
          >
            呼叫
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['call:task:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <CallTaskDrawer @reload="tableApi.query()" />
    <CallTaskDetailsModal
      :width="700"
      :columns="detailsSchema()"
      :api="callTaskInfo"
    >
      <template #completionRate="{ info }">
        <Progress
          :percent="info.completionRate || 0"
          :size="12"
          class="mt-0"
          status="active"
          :stroke-color="{
            from: '#108ee9',
            to: '#87d068',
          }"
        />
      </template>
      <template #smsTemplates="{ info }">
        <Tag
          v-for="item in info.smsTemplates"
          :key="item.id"
          color="blue"
          class="cursor-pointer"
          @click="handlePreviewSms(item.id)"
        >
          <template #icon>
            <MessageOutlined />
          </template>
          {{ item.smsName }}
        </Tag>
      </template>
      <template #emailTemplates="{ info }">
        <Tag
          v-for="item in info.emailTemplates"
          :key="item.id"
          color="blue"
          class="cursor-pointer"
          @click="handlePreviewEmail(item.id)"
        >
          <template #icon>
            <MailOutlined />
          </template>
          {{ item.emailName }}
        </Tag>
      </template>
    </CallTaskDetailsModal>
    <CallTaskDataDrawer @reload="tableApi.query()" />
    <SmsPreviewModal />
    <EmailPreviewModal />
  </Page>
</template>
